<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>    
        function Stack(){
            var items = []; //存储数据

            //从栈顶添加元素，也叫压栈
            this.push=function(item){
                items.push(item);
            };

            //从栈顶移除元素
            this.pop=function(){
                return items.pop();
            }

            //返回栈顶元素
            this.top=function(){
                return items[items.length-1];
            }

            //判断栈是否为空
            this.isEmpty=function(){
                return items.length == 0;
            }

            //返回栈的长度
            this.size=function(){
                return items.length;
            }

            //清空栈
            this.clear=function(){
                items=[];
            }
        }


        var BinTreeNode = function (data){
            this.data = data;
            this.leftChild = null;
            this.rightChild = null;
            this.parentNode = null;
        }
        function BinaryTree(){
              var root = null;
            this.init_tree=function(string){
                var stack = new Stack();
                var k = 0;
                var new_node = null;
                for(var i =0;i<string.length;i++){
                    var item = string[i];
                    if(item == "#"){
                        break;
                    }
                    if(item == "("){
                        stack.push(new_node);
                        k=1;
                    }else if(item == ")"){
                        stack.pop();
                    }else if(item == ","){
                        k=2;
                    }else{
                         new_node = new BinTreeNode(item);
                        if(root == null){
                            root = new_node;
                        }else if(k == 1){
                            //左节点
                            var top_item = stack.top();
                            top_item.leftChild = new_node;
                            new_node.parentNode = top_item;
                        }else if(k == 2){
                            //右节点
                            var top_item = stack.top();
                            top_item.rightChild = new_node;
                            new_node.parentNode = top_item;
                        }
                    }

                }
            }
            
        }
        var a= new BinaryTree();
        console.log(a)
        console.log(a.init_tree("A(B,C(,D))#"))
        console.log(a)
    </script>
</body>
</html>